package com.yiwei.ydd;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.database.ContentObserver;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.widget.Toast;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;


import com.afollestad.materialdialogs.MaterialDialog;
import com.yiwei.ydd.activity.CreateGestureActivity;
import com.yiwei.ydd.activity.VipOrderActivity;
import com.yiwei.ydd.activity.VipOrderPayMoneyActivity;
import com.yiwei.ydd.api.Api;
import com.yiwei.ydd.api.model.PopLevelUpModel;
import com.yiwei.ydd.base.BaseActivity;
import com.yiwei.ydd.constant.Const;
import com.yiwei.ydd.constant.UserInfoGlobal;
import com.yiwei.ydd.event.AddressSelectEvent;
import com.yiwei.ydd.event.ChangePageEvent;
import com.yiwei.ydd.event.LoginSuccessEvent;
import com.yiwei.ydd.event.LogoutEvent;
import com.yiwei.ydd.event.OldUserLoginEvent;
import com.yiwei.ydd.event.RegisterSuccessEvent;
import com.yiwei.ydd.fragment.MainDiscoverFragment;
import com.yiwei.ydd.fragment.MainHomeFragment;
import com.yiwei.ydd.fragment.MainMyFragment;
import com.yiwei.ydd.fragment.ShowDataFragment;
import com.yiwei.ydd.util.AppDownloadManager;
import com.yiwei.ydd.util.Dialog;
import com.yiwei.ydd.util.DownloadUtil;
import com.yiwei.ydd.util.FileUtils;
import com.yiwei.ydd.util.Network;
import com.yiwei.ydd.util.PreferenceUtils;
import com.yiwei.ydd.util.RxLifeUtil;
import com.yiwei.ydd.util.ToastUtil;
import com.yiwei.ydd.util.Util;
import com.yiwei.ydd.view.HomeViewPager;
import com.yiwei.ydd.view.LevelUpDialog;
import com.yiwei.ydd.view.RegisterSuccessDialog;
import com.yiwei.ydd.view.tablayout.MainBottomTabLayout;
import com.yiwei.ydd.view.uploadImage.UploadImgAdapter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class MainActivity extends BaseActivity {

    @BindView(R.id.viewpager)
    HomeViewPager pager;
    @BindView(R.id.tab_bottom)
    MainBottomTabLayout tabBottom;


    private Unbinder unbiner;
    private UploadImgAdapter uploadImgAdapter;
    private MainMyFragment fragmentMy;
    private ShowDataFragment fragmentShowData;
    private MainHomeFragment fragmentHome;

    private AppDownloadManager appDownloadManager;
    private boolean isFirstShow = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initTouMing();
        unbiner = ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        fragmentHome = new MainHomeFragment();
        fragmentShowData = new ShowDataFragment();
        fragmentMy = new MainMyFragment();
        Fragment[] fragments = {fragmentHome, fragmentShowData, fragmentMy};
//        String[] titles = new String[]{"首页", "发现", "我的"};
        pager.setOffscreenPageLimit(2);
        pager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return fragments[position];
            }

            @Override
            public int getCount() {
                return fragments.length;
            }
        });
        tabBottom.setViewPager(pager);
        tabBottom.setOnChooseListener(new MainBottomTabLayout.OnChooseListener() {
            @Override
            public void onClick() {
                if (isFirstShow) {
                    fragmentShowData.getIndexDatas();
                    isFirstShow = false;
                }

            }
        });
        if (UserInfoGlobal.getIsLevelUp()) {
            getPopLevelUp();
        } else {
            if ((!isSetGuesture() || !UserInfoGlobal.getIsOpenGuesture()) && UserInfoGlobal.isLogin()) {
                showGestureDialog();
            }
        }
    }

    public void getPopLevelUp() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();

        Api.api_service.getPopLevelUp().compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    PopLevelUpModel.DatasBean item = result.datas;
                    new LevelUpDialog(this).setData(item.level, item.sale, item.term_sale, item.uolevel_rate, item.utlevel_rate).
                            setDialogClickListener(new LevelUpDialog.DialogDefaultClickListener() {
                                @Override
                                public void confirm() {
                                    Util.startActivity(MainActivity.this, VipOrderActivity.class);
                                }
                            }).show();
                });
    }

    public void getPopBigGif() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();

        Api.api_service.getPopBigGif().compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    if (result.datas != null && result.datas.size() != 0) {
                        new RegisterSuccessDialog(this).setData(result.datas).show();
                    }
                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(AddressSelectEvent event) {
        fragmentHome.setLocation(event.city, event.province);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(LoginSuccessEvent event) {
//        getPopBigGif();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(OldUserLoginEvent event) {
        showGestureDialog();
    }

    private void showGestureDialog() {
        Dialog.showGuestrueDialog(this, "", "设置手势密码可以方便登录，也保障了您的账户安全", "取消", "立即设置", new Dialog.DialogDefaultClickListener() {
            @Override
            public void confirm() {
                Util.startActivity(MainActivity.this, CreateGestureActivity.class);
            }

            @Override
            public void cancel() {

            }
        });
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(RegisterSuccessEvent event) {
        getPopBigGif();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(ChangePageEvent event) {
        pager.setCurrentItem(event.page);
        if (isFirstShow && event.page == 1) {
            fragmentShowData.getIndexDatas();
            isFirstShow = false;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(LogoutEvent event) {
        if (fragmentMy == null) {
            fragmentMy = new MainMyFragment();
        }
        fragmentMy.setLogout();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        unbiner.unbind();
        unbiner = null;
    }

    private void initUploadImgAdapter() {
        uploadImgAdapter = new UploadImgAdapter(this, new UploadImgAdapter.Action2() {
            @Override
            public void call(Bitmap file, int mode) {
                if (mode == UploadImgAdapter.MODE_IMG) {

                }
            }
        });
    }

    public void goToTakePhoto() {
        checkPermission(new CheckPermListener() {
            @Override
            public void superPermission() {
                if (uploadImgAdapter == null) {
                    initUploadImgAdapter();
                }
                uploadImgAdapter.withMode(UploadImgAdapter.MODE_IMG).showDialog();
            }
        }, R.string.camera_storage_card_p, R.string.get_cammra, android.Manifest.permission.CAMERA, android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (uploadImgAdapter != null) {
            uploadImgAdapter.onActivityResult(requestCode, resultCode, data);
        }
    }

    private static long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (System.currentTimeMillis() - exitTime > 2000) {
                ToastUtil.makeText(this,
                        "再按一次退出"
                );
                exitTime = System.currentTimeMillis();
            } else {
                this.finish();
                System.exit(0);
            }
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }


    /**
     * 检查版本
     */
    public void checkUpdate() {
        FileUtils.delFile(Const.APP_NAME); //删除安装包

        String version = PreferenceUtils.getString(this, "lastest_version", "1.0.0");
        String url = PreferenceUtils.getString(this, "download_url", "");


        if (TextUtils.isEmpty(version) || TextUtils.isEmpty(url))
            return;

        try {
            String versionName = Util.getVersion(this);
            versionName = versionName.replace("", "");

            String versionNew = version.replace("", "");

            if (compareVersion(versionNew, versionName) > 0) {
//                isFirstTips = false;

                //注册下载监听
//                receiver = new DownloadBroadcastReceiver();
//                registerReceiver(receiver, new IntentFilter(
//                        DownloadManager.ACTION_DOWNLOAD_COMPLETE));
//
//                showInstallDialog();
                appDownloadManager = new AppDownloadManager(this);
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }

    public static int compareVersion(String version1, String version2) {
        if (version1.equals(version2)) {
            return 0;
        }
        String[] version1Array = version1.split("\\.");
        String[] version2Array = version2.split("\\.");
        int index = 0;
        // 获取最小长度值
        int minLen = Math.min(version1Array.length, version2Array.length);
        int diff = 0;
        // 循环判断每位的大小
        while (index < minLen
                && (diff = Integer.parseInt(version1Array[index])
                - Integer.parseInt(version2Array[index])) == 0) {
            index++;
        }
        if (diff == 0) {
            // 如果位数不一致，比较多余位数
            for (int i = index; i < version1Array.length; i++) {
                if (Integer.parseInt(version1Array[i]) > 0) {
                    return 1;
                }
            }

            for (int i = index; i < version2Array.length; i++) {
                if (Integer.parseInt(version2Array[i]) > 0) {
                    return -1;
                }
            }
            return 0;
        } else {
            return diff > 0 ? 1 : -1;
        }
    }


    /**
     * 获取权限回调 兼容6.0
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 0) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 获取权限成功
                appDownloadManager.initDownloadManager();
            } else {
                // 获取权限失败
                ToastUtil.makeText(this, "获取权限失败~");
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
//        if (materialDialog != null && materialDialog.isShowing()) {
////            isFirstTips = false;
//            return;
//        }
        if (appDownloadManager != null) {
            return;
        }
        checkUpdate();
    }
}
